﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Assets.Scripts.network.socket;
using UnityEngine;
using UnityEngine.Networking;

public class GatewayService : Singleton<GatewayService>
{
    private volatile GatewayInfo gatewayMessage;
    private GatewayClient gatewayClient;

    private event Action<SocketStateEnum> socketStateChangeListener;
    
    

    public IEnumerator SelectGateway( Action callback,Action<ServerError> err)
    {
        GameCenterClient client = GameCenterClient.Instance();
        return client.SendPostRequest(GameCenterClient.SelectGateway,null, data =>
        {
            gatewayMessage = data.ToObject<GatewayInfo>();
            Debug.Log("选择网关成功：" + gatewayMessage);
            callback.Invoke();
        }, error =>
        {
            Debug.Log("连接失败：" + error);
            err.Invoke(error);
        });
    }

   
    public void AddSocketStateChangeListener(Action<SocketStateEnum> action,string tag)
    {
        Debug.Log(tag + " 添加网络状态变化监听");
        socketStateChangeListener += action;
    }
    public void RemoveSocketStateChangeListener(Action<SocketStateEnum> action)
    {
        socketStateChangeListener -= action;
    }
    public void ConnectGateway(SynchronizationContext uiContext, Action<SocketStateEnum> callback)
    {

        if (gatewayMessage == null)
        {
            Debug.LogError("还未选择网关，不能创建连接");
            callback.Invoke(SocketStateEnum.ConnectFailed);
            return;
        }
        if (gatewayClient == null)
        {
            gatewayClient = new GatewayClient(gatewayMessage, uiContext);
            gatewayClient.AddSocketChangeStateListener(socketStateChangeListener, typeof(GatewayService));
        }
        //与网关建立连接
        gatewayClient.Connect((state) =>
        {
            if (state == SocketStateEnum.ConnectSuccess)
            {
                Debug.Log("网关连接成功,开始连接认证!!");
                //连接成功，发送连接认证
                ConfirmClientConnect(() =>
                {
                    
                    callback.Invoke(state);
                });
            } else
            {
                callback.Invoke(state);
            }
            
        });
    }

    public void ConfirmClientConnect(Action callback)
    {
        ConfirmMessageRequest request = new ConfirmMessageRequest();
        request.param.Token = gatewayMessage.Token;
        gatewayClient.Send<ConfirmMessageResponse>(request, (data) =>
        {
            Debug.Log("连接认证成功");
            ConfirmMessageResponse response = (ConfirmMessageResponse)data;
            gatewayMessage.DesSecreteKey = response.param.SecretKey;
            callback.Invoke();

        });

    }

    public void SubscribeServerPushMessageHandler<T>(Action<IGameMessage> callback) where T : IGameMessage
    {
        gatewayClient.SubscribeServerPushMessageHandler<T>(callback);
    }
    public void SendMessage<T>(IGameMessage gameMessage,Action<T> callback) where T : IGameMessage
    {
        gatewayClient.Send<T>(gameMessage, (data)=> {
            T responseMessage = (T)data;
            callback.Invoke(responseMessage);
        });
    }

    public void CloseConnect()
    {
        if(gatewayClient != null)
        {
            gatewayClient.Shutdown();
        }
    }
}
